package com.decent.ejfadmin.product.service.impl;


import com.decent.ejfadmin.common.bean.SupUser;
import com.decent.ejfadmin.common.bean.SupplyProduct;
import com.decent.ejfadmin.common.bean.SupplyProductPrice;
import com.decent.ejfadmin.common.enums.Consts;
import com.decent.ejfadmin.common.enums.SupWebErrorCode;
import com.decent.ejfadmin.common.exception.ErrorCodeException;
import com.decent.ejfadmin.config.PlatConfig;
import com.decent.ejfadmin.product.dao.SupplyProductDao;
import com.decent.ejfadmin.product.service.SupplyProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * describe:
 *
 * @author JunLei He
 * @date 2018年07月11日
 */
@Slf4j
@Service
public class SupplyProductServiceImpl implements SupplyProductService {
    @Autowired
    private SupplyProductDao supplyProductDao;
    @Autowired
    private PlatConfig platConfig;


    /**
     * 查询产品的类型
     *
     * @param area        地区
     * @param face        面值
     * @param productType 类型
     * @return 返回
     */
    @Override
    public SupplyProduct queryProduct(String area, Integer face, Integer productType) {
        SupplyProduct supplyProduct = supplyProductDao.queryProduct(area, face, productType);
        //检测产品
        if (Objects.isNull(supplyProduct)) {
            throw new ErrorCodeException((SupWebErrorCode.Product_NOT_EXIST.getError()));
        }
        //判断产品状态
        if (supplyProduct.getState() == 0) {
            throw new ErrorCodeException(SupWebErrorCode.Product_NOT_OPEN.getError());
        }
        return supplyProduct;
    }


    /**
     * 查询会员折扣
     *
     * @param supUser   sup会员
     * @param productId 产品id
     * @param speed     销卡速度
     * @return
     */
    @Override
    public SupplyProductPrice queryUserProductPrice(SupUser supUser, Long productId, Integer speed) {

        //获取会员单独密价
        SupplyProductPrice productPrice = null;
        if (Consts.SLOW_MODEL.equals(speed) || Consts.FAST_MODEL.equals(speed)) {
            productPrice = supplyProductDao.queryUserProductPrice(supUser.getUserId(), productId);
        }

        //获取会员单独密价
        if (Objects.isNull(productPrice)) {
            Long model = platConfig.supplySpeedParseModel(speed, supUser);
            productPrice = supplyProductDao.queryProductPrice(model, productId);
        }

        //慢销获取快销的最大值
        if (Consts.SLOW_MODEL.equals(speed) && Objects.nonNull(productPrice)) {
            productPrice.setMinPrice(productPrice.getMaxPrice());
        }

        return productPrice;
    }

}
